<template>
    <div class="">
        <div class="crumbs" style="display:inline ;float: left">
            <el-breadcrumb separator="/" >
                <el-breadcrumb-item><i class="el-icon-message"></i> 容器管理</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div style="display:inline;float: right">
            <el-button type="primary" icon="delete" class="handle-del mr10" @click="goToCcntainerCreate">+ 创建新的容器</el-button>
        </div>


        <el-table
            v-loading="loading"
            :data="tableData"
            style="width: 100%">
            <el-table-column
                label="容器名称"
                width="130">
                <template slot-scope="scope">
                    <el-popover >
                        <div slot="reference" class="name-wrapper">
                            {{ scope.row.containerName }}
                        </div>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column
                label="容器状态"
                width="120">
                <template slot-scope="scope">
                    <el-popover >
                        <div slot="reference" class="name-wrapper">
                            <!--{{ scope.row.hasOpen }}-->
                            <el-button
                                size="mini"
                                type="primary" plain
                                >{{ scope.row.status }}</el-button>
                        </div>
                    </el-popover>
                </template>

            </el-table-column>
            <el-table-column
                label="镜像名称"
                width="150">
                <template slot-scope="scope">
                    <el-popover >
                        <div slot="reference" class="name-wrapper">
                            {{ scope.row.imageName }}
                        </div>
                    </el-popover>
                </template>
            </el-table-column>

            <el-table-column
                label="ip地址"
                width="120">
                <template slot-scope="scope">
                    <el-popover >
                        <div slot="reference" class="name-wrapper">
                            {{ scope.row.ip }}
                        </div>
                    </el-popover>
                </template>

            </el-table-column>

            <el-table-column
                label="创建时间"
                width="150">
                <template slot-scope="scope">
                    <el-popover >
                        <div slot="reference" class="name-wrapper">
                            {{ scope.row.createDate }}
                        </div>
                    </el-popover>
                </template>

            </el-table-column>

            <el-table-column
                label="端口"
                width="250">
                <!--<template slot-scope="scope">-->
                    <!--<el-popover >-->
                        <!--<div slot="reference" class="name-wrapper">-->
                            <!--{{ scope.row.port }}-->
                        <!--</div>-->
                    <!--</el-popover>-->
                <!--</template>-->
                <template slot-scope="scope">
                    <el-popover trigger="hover" placement="top">
                        <!--<p></p>-->
                        <el-tag type="success">{{ scope.row.port }}</el-tag>
                        <div slot="reference" class="name-wrapper">
                            <!--<el-tag size="medium"></el-tag>-->
                            {{ scope.row.port }}
                        </div>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column
                label="容器id"
                width="480">
                <template slot-scope="scope">
                    <el-popover >
                        <div slot="reference" class="name-wrapper">
                            <el-tag size="medium">{{ scope.row.containerId }}</el-tag>
                        </div>
                    </el-popover>
                </template>

            </el-table-column>
            <el-table-column label="操作" fixed="right" width="358">
                <template slot-scope="scope">
                    <el-button-group>
                        <el-button type="success" icon="el-icon-success" plain @click="table_start(scope.$index, scope.row)">start</el-button>
                        <el-button type="info" icon="el-icon-warning" @click="table_stop(scope.$index, scope.row)">stop</el-button>
                        <el-button type="success" icon="el-icon-success" @click="table_restart(scope.$index, scope.row)">restart</el-button>
                        <el-button type="warning" icon="el-icon-error" @click="table_kill(scope.$index, scope.row)">kill</el-button>
                        <el-button type="danger" icon="el-icon-delete"  @click="table_delete(scope.$index, scope.row)"></el-button>

                    </el-button-group>
                </template>
            </el-table-column>
            <el-table-column label="更多" fixed="right" width="190">
                <template slot-scope="scope">

                    <el-button-group>
                        <el-button type="primary" round @click="table_getDetails(scope.$index, scope.row)">详情</el-button>
                        <el-button type="primary" round @click="table_getLogs(scope.$index, scope.row)">日志</el-button>
                        <el-button type="primary" round @click="table_openTen(scope.$index, scope.row)">终端</el-button>
                        <!--<el-button type="primary" round plain @click="table_test(scope.$index, scope.row)">test</el-button>-->
                    </el-button-group>

                </template>
            </el-table-column>
        </el-table>

        <!--分页效果-->
        <div class="fenYe">
            <div class="block">
                <el-pagination
                    @current-change="handleCurrentChange"
                    :page-size="5"
                    layout="prev, pager, next, jumper"
                    :total="listTotal">
                </el-pagination>
            </div>
        </div>

        <!--详情提示框-->
        <el-dialog
            title="详细信息"
            :visible.sync="dialogVisible"
            width="50%"
            :before-close="handleClose">

            <div id="editor" class="json-editor"></div>
            <pre id="json"></pre>

            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
            </span>
        </el-dialog>

        <!--详情提示框-->
        <el-dialog
            title="日志信息"
            :visible.sync="dialogVisible1"
            width="100%"
            :before-close="handleClose">

            <textarea style="width: 100%; height: 450px">{{logs}}</textarea>


            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible1 = false">取 消</el-button>
                <el-button type="primary" @click="dialogVisible1 = false">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
    import store from '../../vuex/store'
    import '../../../static/js/jsoneditor'
    import Permission from "./Permission";
    export default {

        name: 'tabs',
        components: {Permission},
        data() {
            return {
                tableData: [],
                listTotal:0,
                currentPage:1,
                dialogVisible:false,
                dialogVisible1:false,
                logs:"",
                userId:"",
                loading:true,

            }
        },
        methods: {

            handleCurrentChange(val) {
                this.getAllContainer(val);
                store.state.ContainerCurrentPage = val;
            },
            table_start(index,row) {
                this.startContainer(row.containerId);
            },
            table_stop(index,row) {
                this.stopContainer(row.containerId);
            },
            table_restart(index,row) {
                this.restartContainer(row.containerId);
            },
            //强制关闭
            table_kill(index,row) {
                this.killContainer(row.containerId);
            },

            table_getLogs(index,row) {
                this.getContainerLogs(row.containerId);
            },
            table_openTen(index,row) {
                this.openTerminal(row.containerId);
            },
            //删除容器
            table_delete(index,row) {
                this.$confirm('确认删除？')
                    .then(_ => {


                        var token='Bearer '+sessionStorage.getItem("Token");
                        let config = {
                            headers: {
                                'Authorization':token,
                            }
                        };
                        var url = "/api/docker/customer/removeContainer"+"?containerId="+row.containerId;
                        this.$axios.get(url,config).then(res=>{
                            console.log(res);
                            if(res.data.code===1) {
                                this.$message.success("成功删除该容器");
                                this.getAllContainer(store.state.ContainerCurrentPage);
                            } else {
                                this.$message.error(res.data.msg);
                            }
                        }).catch(reason => {
                            console.log(reason);
                            this.$message.error(reason.data.msg);
                        })

                    })
                    .catch(_ => {});
            },

            table_getDetails(index,row) {
                this.getContainerDetails(row.containerId);
            },
            handleClose(done) {
                this.$confirm('确认关闭？')
                    .then(_ => {
                        done();
                    })
                    .catch(_ => {});
            },

            goToCcntainerCreate() {
                this.$router.push({path: '/containerCreate'});//跳转页面
            },



            //获取私人容器列表,分页
            getAllContainer(val){

                var token='Bearer '+sessionStorage.getItem("Token");
                let config = {
                    headers: {
                        'Authorization':token,
                    }
                };
                var url = "/api/docker/customer/listSelfAllContainers?pageIndex="+val;
                this.$axios.get(url,config)
                    .then(res=>{
                        if (res.data.code === 1) {
                            this.tableData = res.data.data;
                            for (var i=0; i<this.tableData.length; i++){
                                this.tableData[i].ip = store.state.service_address;
                                if (this.tableData[i].status===0) {
                                    this.tableData[i].status="关闭"
                                }
                                if (this.tableData[i].status===1) {
                                    this.tableData[i].status="运行"
                                }
                            }
                            this.loading=false;
                        }

                })
                    .catch(function (err) {
                        console.log(err);
                    })
            },

            //获取私人容器列表的总数
            getSelfContainerTotal() {
                var token='Bearer '+sessionStorage.getItem("Token");
                let config = {
                    headers: {
                        'Authorization':token,
                    }
                };
                var url = "/api/docker/customer/getSelfContainerTotal";
                this.$axios.get(url,config).then(res=>{
                    console.log(res);
                    if(res.data.code===1) {
                        this.$message.success("成功获取私人容器总数");
                        this.listTotal=res.data.data;

                    } else {
                        this.$message.error("获取私人容器总数失败");
                    }
                }).catch(reason => {
                    console.log(reason);
                    this.$message.error("获取私人容器总数失败");
                })
            },
            //启动容器
            startContainer(val) {
                var token='Bearer '+sessionStorage.getItem("Token");
                let config = {
                    headers: {
                        'Authorization':token,
                    }
                };
                var url = "/api/docker/customer/startContainer?containerId="+val;
                this.$axios.get(url,config).then(res=>{
                    console.log(res);
                    if(res.data.code===1) {
                        this.$message.success(res.data.data);
                        // this.listTotal=res.data.data;
                        this.getAllContainer( store.state.ContainerCurrentPage);

                    } else {
                        this.$message.error(res.data.msg);
                        this.getAllContainer( store.state.ContainerCurrentPage);
                    }
                }).catch(reason => {
                    console.log(reason);
                    this.$message.error(reason.data.msg);
                    this.getAllContainer( store.state.ContainerCurrentPage);
                })
            },
            //停止容器
            stopContainer(val) {
                var token='Bearer '+sessionStorage.getItem("Token");
                let config = {
                    headers: {
                        'Authorization':token,
                    }
                };
                var url = "/api/docker/customer/stopContainer?containerId="+val;
                this.$axios.get(url,config).then(res=>{
                    console.log(res);
                    if(res.data.code===1) {
                        this.$message.success("关闭容器成功");
                        // this.listTotal=res.data.data;
                        this.getAllContainer( store.state.ContainerCurrentPage);

                    } else {
                        this.$message.error(res.data.msg);
                        this.getAllContainer( store.state.ContainerCurrentPage);
                    }
                }).catch(reason => {
                    console.log(reason);
                    this.$message.error(reason.data.msg);
                    this.getAllContainer( store.state.ContainerCurrentPage);
                })
            },
            //重启容器
            restartContainer(val) {
                var token='Bearer '+sessionStorage.getItem("Token");
                let config = {
                    headers: {
                        'Authorization':token,
                    }
                };
                var url = "/api/docker/customer/restartContainer?containerId="+val;
                this.$axios.get(url,config).then(res=>{
                    console.log(res);
                    if(res.data.code===1) {
                        this.$message.success("重启容器成功");
                        // this.listTotal=res.data.data;
                        this.getAllContainer( store.state.ContainerCurrentPage);

                    } else {
                        this.$message.error(res.data.msg);
                        this.getAllContainer( store.state.ContainerCurrentPage);
                    }
                }).catch(reason => {
                    console.log(reason);
                    this.$message.error(reason.data.msg);
                    this.getAllContainer( store.state.ContainerCurrentPage);
                })
            },
            //强制停止容器
            killContainer(val) {
                var token='Bearer '+sessionStorage.getItem("Token");
                let config = {
                    headers: {
                        'Authorization':token,
                    }
                };
                var url = "/api/docker/customer/killContainer?containerId="+val;
                this.$axios.get(url,config).then(res=>{
                    console.log(res);
                    if(res.data.code===1) {
                        this.$message.success("强制停止容器成功");
                        // this.listTotal=res.data.data;
                        this.getAllContainer( store.state.ContainerCurrentPage);

                    } else {
                        this.$message.error(res.data.msg);
                        this.getAllContainer( store.state.ContainerCurrentPage);
                    }
                }).catch(reason => {
                    console.log(reason);
                    this.$message.error(reason.data.msg);
                    this.getAllContainer( store.state.ContainerCurrentPage);
                })
            },
            //获取容器的详细信息
            getContainerDetails(val) {
                this.dialogVisible=true;
                var token='Bearer '+sessionStorage.getItem("Token");
                let config = {
                    headers: {
                        'Authorization':token,
                    }
                };
                var url = "/api/docker/customer/inspectContainer?containerId="+val;
                this.$axios.get(url,config).then(res=>{
                    console.log(res);
                    if(res.data.code===1) {
                        this.$message.success("获取容器详细成功");

                        let json = res.data.data;
                        $('#editor').jsonEditor(json, {
                            change: function () {
                                $('#json').html(JSON.stringify(json));
                            }
                        });

                    } else {
                        this.$message.error(res.data.msg);
                        // this.getAllContainer( store.state.ContainerCurrentPage);
                    }
                }).catch(reason => {
                    console.log(reason);
                    this.$message.error(reason.data.msg);
                    // this.getAllContainer( store.state.ContainerCurrentPage);
                })

            },
            //获取容器日志信息
            getContainerLogs(val) {

                this.dialogVisible1=true;
                var token='Bearer '+sessionStorage.getItem("Token");
                let config = {
                    headers: {
                        'Authorization':token,
                    }
                };
                var url = "/api/docker/customer/getContainerLogs?containerId="+val;
                this.$axios.get(url,config).then(res=>{
                    // console.log(res.data.data);
                    if(res.data.code===1) {
                        this.$message.success("获取容器日志成功");

                        this.logs = res.data.data;


                    } else {
                        this.$message.error(res.data.msg);
                        // this.getAllContainer( store.state.ContainerCurrentPage);
                    }
                }).catch(reason => {
                    console.log(reason);
                    // this.$message.error(reason.data.msg);
                    // this.getAllContainer( store.state.ContainerCurrentPage);
                })

            },
            //打开终端
            openTerminal(val) {
                var token='Bearer '+sessionStorage.getItem("Token");
                let config = {
                    headers: {
                        'Authorization':token,
                    }
                };

                var fd = new FormData();
                fd.append("containerId",val);
                fd.append("cursorBlink",false);
                fd.append("rows",50);
                fd.append("cols",200);
                fd.append("width", document.documentElement.clientWidth);
                fd.append("height",document.documentElement.clientHeight);

                var url = "/api/docker/customer/terminal";
                this.$axios.post(url,fd,config).then(res=>{
                    console.log(res);
                    if(res.data.code===1) {
                        this.$message.success("打开终端成功");
                        sessionStorage.setItem('terminalCursorBlink', res.data.data.cursorBlink);
                        sessionStorage.setItem('terminalRows',res.data.data.rows);
                        sessionStorage.setItem('terminalCols',res.data.data.cols);
                        sessionStorage.setItem('terminalUrl',res.data.data.url);
                        window.open('../../../static/term.html');


                    } else {
                        this.$message.error(res.data.msg);

                    }
                }).catch(reason => {
                    console.log(reason);
                    this.$message.error(reason.data.msg);

                })

            },
            //连接websocket
            conectWebSocket(){

                var token='Bearer '+sessionStorage.getItem("Token");
                let config = {
                    headers: {
                        'Authorization':token,
                    }
                };
                console.log(token);
                var url = "/api/user/getPersonalInfo";
                console.log(url);
                this.$axios.get(url,config).then(res=> {
                    console.log(res);
                    if(res.data.code===1) {
                        this.userId = res.data.data.id;
                        this.websock = new WebSocket("ws://localhost:8082"+"/ws/"+this.userId);

                        this.websock.onopen = this.websocketonopen;

                        // this.websock.onerror = this.websocketonerror;

                        this.websock.onmessage = this.websocketonmessage;

                        this.websock.onclose = this.websocketclose;

                    } else {
                        this.$message.error(res.data.msg);
                    }
                }).catch( res => {
                    console.log(res);
                    this.$message.error(res.data.msg);
                })
            },

            websocketonopen:function() {
                console.log("WebSocket连接成功");
            },

            websocketonerror:function(e) { //错误
                console.log("WebSocket连接发生错误");
            },

            //todo
            websocketonmessage:function(e){ //数据接收
                console.log(e.data);
                if(e.data=="容器启动成功!") {
                    this.getAllContainer( store.state.ContainerCurrentPage);
                }

                this.$notify.info({
                title: '消息推送',
                message: e.data
                });
            },

            websocketsend:function(agentData){//数据发送
                this.websock.send(agentData);
            },

            websocketclose:function(e){ //关闭
                console.log("connection closed (" + e.code + ")");
            },

            //测试
            table_test() {
                var token='Bearer '+sessionStorage.getItem("Token");
                let config = {
                    headers: {
                        'Authorization':token,
                    }
                };
                var url = "/api/docker/test/222";
                this.$axios.get(url,config).then(res=>{
                    console.log(res);
                    if(res.data.code===1) {
                        this.$message.success("test");
                        this.logs = res.data.data;
                    } else {
                        this.$message.error(res.data.msg);
                        // this.getAllContainer( store.state.ContainerCurrentPage);
                    }
                }).catch(reason => {
                    console.log(reason);
                    // this.$message.error(reason.data.msg);
                    // this.getAllContainer( store.state.ContainerCurrentPage);
                })
            },

    },
        computed: {

        },
        created(){
            this.conectWebSocket();
            this.getAllContainer(store.state.ContainerCurrentPage);
            this.getSelfContainerTotal();
        }
    }

</script>

<style>

</style>

